"use client"

import { useState, useEffect } from "react"
import { FileList } from "@/components/file-list"
import { Breadcrumb } from "@/components/breadcrumb"
import { apiCall, mockGenerators } from "@/lib/mock-api"
import { toast } from "@/hooks/use-toast"

interface FileExplorerProps {
  folderId: number
  onFolderChange: (id: number) => void
  searchQuery: string
  refreshKey?: number
}

export function FileExplorer({ folderId, onFolderChange, searchQuery, refreshKey = 0 }: FileExplorerProps) {
  const [files, setFiles] = useState<any[]>([])
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    loadFiles()
  }, [folderId, searchQuery, refreshKey])

  const loadFiles = async () => {
    setIsLoading(true)
    try {
      const url = searchQuery
        ? `/api/search?keyword=${encodeURIComponent(searchQuery)}`
        : `/api/files?parentId=${folderId}`

      const data = await apiCall(
        url,
        undefined,
        undefined,
        searchQuery ? () => mockGenerators.search(searchQuery) : mockGenerators.files,
      )

      const filesData = Array.isArray(data) ? data : []
      setFiles(filesData)
    } catch (error) {
      console.error("Failed to load files:", error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleDelete = async (fileId: number) => {
    try {
      await apiCall(
        `/api/files/${fileId}`,
        {
          method: "DELETE",
        },
        { success: true },
      )

      toast({
        title: "删除成功",
        description: "文件已删除",
        variant: "success",
        duration: 3000,
      })
      loadFiles()
    } catch (error) {
      console.error("Failed to delete file:", error)
    }
  }

  const handleRename = async (fileId: number, newName: string) => {
    try {
      await apiCall(
        `/api/files/${fileId}`,
        {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ newName }),
        },
        { success: true },
      )

      toast({
        title: "重命名成功",
        description: `文件已重命名为: ${newName}`,
        variant: "success",
        duration: 3000,
      })
      loadFiles()
    } catch (error) {
      console.error("Failed to rename file:", error)
    }
  }

  const handleDownload = async (fileId: number, fileName: string) => {
    try {
      // toast({
      //   title: "开始下载",
      //   description: `正在下载: ${fileName}`,
      //   variant: "info",
      //   duration: 3000,
      // })

      // 获取 token
      const token = localStorage.getItem("driveJWTToken")
      const downloadUrl = `/api/files/download/${fileId}`

      // 使用 fetch 下载文件，添加认证头
      const response = await fetch(downloadUrl, {
        method: "GET",
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })

      if (!response.ok) {
        throw new Error(`下载失败: ${response.status}`)
      }

      // 获取文件内容
      const blob = await response.blob()

      // 创建 Blob URL
      const blobUrl = window.URL.createObjectURL(blob)

      // 在新窗口打开文件
      // const newWindow = window.open(blobUrl, "_blank")

      // 如果浏览器阻止了弹窗，使用下载方式
      // if (!newWindow) {
        // 创建一个隐藏的 a 标签进行下载
        const link = document.createElement("a")
        link.href = blobUrl
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      // }

      // 清理 Blob URL（延迟清理，确保窗口已打开）
      setTimeout(() => {
        window.URL.revokeObjectURL(blobUrl)
      }, 100)

      toast({
        title: "下载成功",
        description: `${fileName} 已下载`,
        variant: "success",
        duration: 3000,
      })
    } catch (error) {
      console.error("Failed to download file:", error)
      toast({
        title: "下载失败",
        description: `无法下载文件: ${fileName}`,
        variant: "destructive",
        duration: 3000,
      })
    }
  }

  return (
    <main className="flex-1 overflow-auto p-6">
      <Breadcrumb folderId={folderId} onNavigate={onFolderChange} />
      <FileList
        files={files}
        isLoading={isLoading}
        onFolderOpen={onFolderChange}
        onDelete={handleDelete}
        onRename={handleRename}
        onDownload={handleDownload}
        onRefresh={loadFiles}
      />
    </main>
  )
}
